<template>
  <view class="business-license-container">
    <!-- 顶部提示 -->
    <view class="tips-card">
      <view class="tips-icon">
        <uni-icons type="info-filled" size="20" color="#1890ff"></uni-icons>
      </view>
      <view class="tips-content">
        <text class="tips-title">上传须知</text>
        <text class="tips-text">1. 请上传清晰的营业执照正本或副本照片</text>
        <text class="tips-text">2. 确保营业执照信息完整可见</text>
        <text class="tips-text">3. 支持JPG、PNG格式，大小不超过5MB</text>
        <text class="tips-text">4. 上传后系统将自动添加水印保护</text>
      </view>
    </view>

    <!-- 营业执照展示区 -->
    <view class="license-section">
      <view class="section-header">
        <text class="section-title">营业执照</text>
        <!-- <view v-if="businessLicense.status === '1'" class="status-badge success">
          <uni-icons type="checkmarkempty" size="14" color="#52c41a"></uni-icons>
          <text class="status-text">已认证</text>
        </view>
        <view v-else-if="businessLicense.status === '0'" class="status-badge warning">
          <uni-icons type="info" size="14" color="#faad14"></uni-icons>
          <text class="status-text">待审核</text>
        </view>
        <view v-else-if="businessLicense.status === '2'" class="status-badge warning">
          <uni-icons type="info" size="14" color="#faad14"></uni-icons>
          <text class="status-text">被驳回</text>
        </view> -->
      </view>

      <view v-if="businessLicense.status === '2'" class="reject-reason">
        <text>驳回原因：{{ businessLicense.rejectReason }}</text>
      </view>

      <!-- 图片上传组件 -->
      <image-uploader
        ref="licenseUploader"
        :upload-type="'watermark'"
        :upload-text="'点击上传营业执照'"
        :upload-hint="'请上传清晰的营业执照照片'"
        :initial-image-url="businessLicense.imageUrl"
        @upload-complete="handleImageUploadComplete"
        @upload-error="handleImageUploadError"
      />

      <!-- 企业信息表单 -->
      <view v-if="businessLicense.imageUrl" class="license-info">
        <view class="info-item">
          <text class="info-label">企业名称：</text>
          <input class="info-input" v-model="businessLicense.companyName" placeholder="请输入企业名称" @blur="saveBusinessLicense" />
        </view>
        <view class="info-item">
          <text class="info-label">信用代码：</text>
          <input
            class="info-input"
            v-model="businessLicense.creditCode"
            placeholder="请输入统一社会信用代码"
            maxlength="18"
            @blur="saveBusinessLicense"
          />
        </view>
        <view v-if="businessLicense.uploadTime" class="info-item">
          <text class="info-label">上传时间：</text>
          <text class="info-value">{{ businessLicense.uploadTime }}</text>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button v-if="businessLicense.imageUrl && businessLicense.status !== '1'" class="btn-submit" @click="submitForReview">提交审核</button>
    </view>
  </view>
</template>

<script>
import { isHttp } from '@/utils/validate';
import config from '@/config';
import ImageUploader from '@/components/image-uploader.vue';
const baseUrl = config.baseUrl;

export default {
  components: {
    ImageUploader
  },
  
  data() {
    return {
      businessLicense: {
        imageUrl: '',
        companyName: '',
        creditCode: '',
        legalPerson: '',
        validUntil: '',
        uploadTime: '',
        status: '', // 0-待审核, 1-已认证, 2-审核失败
      },
      // historyList: []  // 不再使用历史记录
    };
  },

  onLoad() {
    this.loadBusinessLicense();
  },

  methods: {
    // 加载营业执照信息
    async loadBusinessLicense() {
      try {
        uni.showLoading({ title: '加载中...' });
        const res = await this.$http.get('/system/merchant/businessLicense');
        if (res.code === 200 && res.data) {
          this.businessLicense = res.data;
          // 不再使用历史记录
          // this.historyList = res.data.historyList || []
        }
      } catch (error) {
        console.error('加载营业执照失败:', error);
      } finally {
        uni.hideLoading();
      }
    },

    // 图片上传完成处理
    handleImageUploadComplete(imageUrl) {
      this.businessLicense.imageUrl = imageUrl;
      
      // 如果图片被删除（空字符串），清空相关信息
      if (!imageUrl) {
        this.businessLicense.companyName = '';
        this.businessLicense.creditCode = '';
        this.businessLicense.uploadTime = '';
        this.businessLicense.status = '';
      }

      this.saveBusinessLicense()
      // 不再自动保存，统一在提交审核时保存
    },

    // 图片上传错误处理
    handleImageUploadError(error) {
      console.error('图片上传失败:', error);
      // 可以根据错误类型进行不同的提示
      if (error.message && error.message.includes('大小')) {
        uni.showToast({
          title: error.message,
          icon: 'none',
        });
      } else {
        uni.showToast({
          title: '上传失败，请重试',
          icon: 'none',
        });
      }
    },

    // 保存营业执照信息
    async saveBusinessLicense() {
      try {
        const res = await this.$http.post('/system/merchant/businessLicense', {
          imageUrl: this.businessLicense.imageUrl,
          companyName: this.businessLicense.companyName,
          creditCode: this.businessLicense.creditCode,
          legalPerson: this.businessLicense.legalPerson,
          validUntil: this.businessLicense.validUntil,
          status: '0', // 待审核
        });

        if (res.code === 200) {
          // 保留用户输入的数据
          const userInput = {
            companyName: this.businessLicense.companyName,
            creditCode: this.businessLicense.creditCode,
          };
          this.businessLicense = { ...res.data, ...userInput };
        }
      } catch (error) {
        console.error('保存营业执照失败:', error);
      }
    },

    // 预览图片
    previewImage() {
      if (this.businessLicense.imageUrl) {
        uni.previewImage({
          urls: [this.businessLicense.imageUrl],
          current: 0,
        });
      }
    },

    // 提交审核
    async submitForReview() {
      // 先保存营业执照信息
      try {
        uni.showLoading({ title: '保存中...' });
        const saveRes = await this.$http.post('/system/merchant/businessLicense', {
          imageUrl: this.businessLicense.imageUrl,
          companyName: this.businessLicense.companyName,
          creditCode: this.businessLicense.creditCode,
          legalPerson: this.businessLicense.legalPerson,
          validUntil: this.businessLicense.validUntil,
          status: '0', // 待审核
        });

        if (saveRes.code === 200) {
          // 保存成功后提交审核
          uni.showModal({
            title: '确认提交',
            content: '确定要提交营业执照进行审核吗？',
            success: async (res) => {
              if (res.confirm) {
                try {
                  uni.showLoading({ title: '提交中...' });
                  const response = await this.$http.post('/system/merchant/businessLicense/submit');

                  if (response.code === 200) {
                    uni.showToast({
                      title: '提交成功',
                      icon: 'success',
                    });
                    this.businessLicense.status = '0'; // 待审核
                  } else {
                    uni.showToast({
                      title: response.msg || '提交失败',
                      icon: 'none',
                    });
                  }
                } catch (error) {
                  console.error('提交失败:', error);
                  uni.showToast({
                    title: '提交失败',
                    icon: 'none',
                  });
                } finally {
                  uni.hideLoading();
                }
              }
            },
          });
        } else {
          uni.showToast({
            title: saveRes.msg || '保存失败',
            icon: 'none',
          });
        }
      } catch (error) {
        console.error('保存营业执照失败:', error);
        uni.showToast({
          title: '保存失败，请重试',
          icon: 'none',
        });
      } finally {
        uni.hideLoading();
      }
    },
  },
};
</script>

<style scoped>
.business-license-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 100rpx;
}

/* 提示卡片 */
.tips-card {
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 24rpx;
  display: flex;
  align-items: flex-start;
}

.tips-icon {
  margin-right: 16rpx;
  margin-top: 4rpx;
}

.tips-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.tips-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #1565c0;
  margin-bottom: 12rpx;
}

.tips-text {
  font-size: 26rpx;
  color: #1976d2;
  line-height: 1.6;
  margin-bottom: 8rpx;
}

/* 执照展示区 */
.license-section {
  background: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.status-badge {
  display: flex;
  align-items: center;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
}

.status-badge.success {
  background: #f6ffed;
  border: 1rpx solid #b7eb8f;
}

.status-badge.warning {
  background: #fffbe6;
  border: 1rpx solid #ffe58f;
}
.status-badge.warning {
  background: #fff1e6;
  border: 1rpx solid #ee0505;
}

.reject-reason{
  margin-bottom: 10rpx;
  color: #ee0505;
  font-size: 24rpx;
}

.status-text {
  font-size: 24rpx;
  margin-left: 8rpx;
}

/* 执照预览 */
.license-preview {
  border-radius: 16rpx;
  overflow: hidden;
  background: linear-gradient(135deg, #f8fafb 0%, #ffffff 100%);
  border: 2rpx solid #e1e8ee;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.license-image {
  width: 100%;
  height: 400rpx;
  background: linear-gradient(135deg, #f8fafb 0%, #ffffff 100%);
}

.license-info {
  padding: 24rpx;
  background: linear-gradient(135deg, #f6f8fb 0%, #ffffff 100%);
  border-top: 1rpx solid #e8ecf0;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  padding: 12rpx 0;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-label {
  width: 140rpx;
  font-size: 26rpx;
  color: #666;
  margin-right: 16rpx;
  text-align: right;
}

.info-value {
  font-size: 26rpx;
  color: #333;
  flex: 1;
}

.info-input {
  flex: 1;
  height: 72rpx;
  padding: 0 24rpx;
  font-size: 28rpx;
  background: #ffffff;
  border: 2rpx solid #e1e8ee;
  border-radius: 8rpx;
  transition: all 0.3s;
}

.info-input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 4rpx rgba(24, 144, 255, 0.1);
}



/* 操作按钮 */
.action-buttons {
  margin: 20rpx;
  display: flex;
  gap: 30rpx; /* 增加按钮间距 */
}

.btn-submit {
  flex: 1;
  height: 88rpx;
  border-radius: 44rpx;
  font-size: 30rpx;
  font-weight: bold;
  border: none;
}

.btn-submit {
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
  color: #fff;
}
</style>
